class Dep {
  constructor() {
    this.subscribers = new Set()
  }

  addEffect(effect) {
    this.subscribers.add(effect)
  }

  depend() {
    if (activeEffect) {
      this.subscribers.add(activeEffect)
    }
  }

  notify() {
    this.subscribers.forEach(effect => {
      effect()
    })
  }

}

let activeEffect = null
function watchEffect(effect) {
  activeEffect = effect
  effect()
  activeEffect = null
}

// Map(key: value) key是字符串
// WeakMap(key: valye) : key是一个对象，弱引用
const targetMap = new WeakMap()
function getDep(target, key) {
  // 1.根据对象取出对应map值
  let depsMap = targetMap.get(target)
  if (!depsMap) {
    depsMap = new Map()
    targetMap.set(target, depsMap)
  }
  // 2.取出具体的dep对象
  let dep = depsMap.get(key)
  if (!dep) {
    dep = new Dep()
    depsMap.set(key, dep)
  }
  return dep
}


// vue2 对数据进行劫持
function reactive(raw) {
  return new Proxy(raw, {
    get(target, key) {
      const dep = getDep(target, key)
      dep.depend()
      return target[key]
    },
    set(target, key, newValue) {
      const dep = getDep(target, key)
      target[key] = newValue
      dep.notify()
    }
  })
}

const dep = new Dep()

// 测试代码
// const info = reactive({ counter: 100, name: 'aaa' })
// const foo = reactive({height: 110})


// watchEffect(function () {
//   console.log('effct1', info.counter * 2, info.name)
// })
// watchEffect(function () {
//   console.log('effct2',info.counter * info.counter)
// })
// watchEffect(function () {
//   console.log('effct3', foo.height)
// })
// info.counter++